import webpack              from 'webpack';
import express              from 'express';
import WebpackDevMiddleware from 'webpack-dev-middleware';
import WebpackHotMiddleware from 'webpack-hot-middleware';

import webpackConfig        from '../webpack.config';

const env                   = process.env;
// set compiler build
const compiler              = webpack( webpackConfig );
// create server of express
const app                   = express();

const devConfig             = {};
devConfig.publicPath        = webpackConfig.output.publicPath;
devConfig.stats             = { colors : true };
devConfig.hot               = true;
devConfig.quiet             = false;
devConfig.noInfo            = false;
devConfig.lazy              = false;
// create hot middleware and dev middleware
const hotMiddleware         = WebpackHotMiddleware( compiler);
const devMiddleware         = WebpackDevMiddleware( compiler, devConfig );

// add event
compiler.plugin('compilation', ( compilation ) => {
  compilation.plugin( 'html-webpack-plugin-after-emit', ( data, cb ) => {
    console.log(hotMiddleware, "=============");
    hotMiddleware.publish({ action : 'reload' });
    cb();
  });
});

// http use dev and hot loading
app.use( devMiddleware );
app.use( hotMiddleware );

// listen port
app.listen( env.PORT_DEVELOP, () => {
  console.log( `Listening on ${env.PORT_DEVELOP}` );
});
